import React, { Component } from "react";
import PropTypes from "prop-types";
import axios from "axios";

class AuthorsArea extends Component {
  static propTypes = {
    searchName: PropTypes.string.isRequired,
  };
  // 1.分析组件状态,
  //1.1 一开始提示状态
  //1.2 搜索中状态
  //1.3 搜索结果出来的状态
  //1.4 和搜索失败的状态
  state = {
    //请输入作者的文本
    initView: true,
    //点击搜索后,显示搜索中文本
    loading: false,
    //搜索完得到list
    users: null,
    //如果搜索出错了
    errorMsg: null,
  };
  componentWillReceiveProps(nextProps) {
    const { searchName } = nextProps;
    this.setState({
      initView: false,
      loading: true,
    });
    let url = `https://api.github.com/search/users?q=${searchName}`;
    axios
      .get(url)
      .then((res) => {
        //得到响应数据
        const reult = res.data;
        const users = reult.items.map((item, index) => ({
          name: item.login,
          url: item.html_url,
          avatarUrl: item.avatar_url,
        }));
        //更新状态
        this.setState({
          loading: false,
          users,
        });
      })
      .catch((error) => {
        //更新失败的状态
        this.setState({
          errorMsg: error.message,
          loading: false,
        });
      });
    // fetch(url)
    //   .then((res) => res.json())
    //   .then((res) => {
    //     console.log(res);
    //     // const reult = res.data;
    //   })
    //   .catch((error) => {
    //     //     //更新失败的状态
    //     this.setState({
    //       errorMsg: error.message,
    //       //       // loading: true,
    //     });
    //   });
  }

  render() {
    const { initView, loading, users, errorMsg } = this.state;
    const { searchName } = this.props;
    if (initView) {
      return <h2>请输入关键字进行搜索 {searchName}</h2>;
    } else if (loading) {
      return <h2>正在搜索中....</h2>;
    } else if (errorMsg) {
      return <h2>{errorMsg}</h2>;
    } else {
      return (
        <div className="row">
          {users.map((user, index) => (
            <div
              className="card"
              key={index}
              style={{
                width: "100px",
                display: "inline-block",
                margin: "10px 10px",
              }}
            >
              <a href={user.url} target="_brank">
                <img
                  src={user.avatarUrl}
                  alt="用户头像"
                  style={{ width: 100 }}
                />
              </a>
              <p className="card-text">{user.name}</p>
            </div>
          ))}
        </div>
      );
    }
  }
}

export default AuthorsArea;
